package com.java.geteway.filter;

import com.alibaba.fastjson.JSONObject;
import com.java.common.util.JwtUtil;
import com.java.common.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(1)
public class LoginFilter implements GlobalFilter {

    private static AntPathMatcher matcher = new AntPathMatcher();

    /*@Autowired
    private RedisTemplate redisTemplate;*/

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 不需要拦截的url直接放行
        if (needLogin(request.getPath().toString())) {
            return chain.filter(exchange);
        }

        // 获取请求头对象
        HttpHeaders headers = exchange.getRequest().getHeaders();
        // 获取Token
        String token = headers.getFirst("Token");
        if (StringUtils.isNotBlank(token)) {
            // 判断Token是否合法
            /*String id = token.substring(32);
            String redisToken = RedisUtil.getString(redisTemplate, "admin_" + id);
            if (token.equals(redisToken)) {
                // 更新Token的有效期
                RedisUtil.setTimeout(redisTemplate, "admin_" + id, 30L);

                // 合法 -> 放行
                return chain.filter(exchange);
            }*/
            if (JwtUtil.verifyToken(token)) {
                // 合法 -> 放行
                return chain.filter(exchange);
            }
        }

        // 不合法 -> 拦截
        return loginResponse(exchange);
    }

    public static Mono<Void> loginResponse(ServerWebExchange exchange) {
        JSONObject resultJson = new JSONObject();
        resultJson.put("code", "403");
        resultJson.put("message", "请重新登陆授权");
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = JSONObject.toJSONBytes(resultJson);
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Flux.just(buffer));
    }

    public static boolean needLogin(String uri) {
        List<String> uriList = new ArrayList<>();
        uriList.add("/user/login");
        uriList.add("/user/list");
        uriList.add("/role/listAll");
        uriList.add("/brand/brandList");
        uriList.add("/color/colorList");
        uriList.add("/License/plateList");
        uriList.add("/model/modelList");
        uriList.add("/company/listAll");
        uriList.add("/appointment/save");

        for (String pattern : uriList) {
            // 不需要拦截
            if (matcher.match(pattern, uri)) {
                return true;
            }
        }

        return false;
    }

}
